<?php


namespace app\api\controller;

use app\api\model\AccountModel;
use app\api\model\UserModel;
use app\api\validate\LoginValidate;
use app\common\controller\Auth;
use think\facade\Cache;

// 引入解密文件 在微信小程序开发文档下载
require_once "../vendor/WeMini/crypt/wxBizDataCrypt.php";
require_once "../vendor/WeMini/crypt/errorCode.php";
class Login extends ApiBase
{

    const APPID = '111111';
    const SECRET = '222222';
    /**
     *
     * 获取用户手机号
     */
    public function getPhone($code){

        $res = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$res['access_token'];
        $code1['code'] = $code;
        $info = post(json_encode($code1),$url);
        $data = json_decode($info,true);
        //$data['open_id'] =
        if ($data['errcode'] == 0){

            return $data;
        }else{

            $this->fail('获取手机号失败');
        }
    }


    /**
     *
     * 获取open_id
     */
    public function getOpenId($code){

        $appid = config('WeiXin')['appId'];
        $appsecret = config('WeiXin')['appSecret'];
        $grant_type = "authorization_code"; //授权（必填）
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        return $res;
    }
    /**
     * 授权登录
     */
    public function login(){
        $params = $this->request->post();
        if (!isset($params['code']) || $params['code'] == ''){

            $this->fail('缺少必要参数code');
        }
        if (!isset($params['code1']) || $params['code1'] == ''){

            $this->fail('缺少必要参数code1');
        }
        $open_id = self::getOpenId($params['code']);
        $data = self::getPhone($params['code1']);

        if (is_array($open_id)) {

            if (!UserModel::userInfo(['phone' => $data['phone_info']['phoneNumber']])) {

                //$info['union_id'] = $open_id['unionid'];
                $info['open_id'] = $open_id['openid'];
                $info['phone'] = $data['phone_info']['phoneNumber'];
                //$info['pid'] = isset($params['pid']) ? $params['pid'] : 0;
                $user_id = UserModel::insertGetId($info);

                $userInfo = UserModel::userInfo(['id' => $user_id]);
            }else{
                //$info['union_id'] = $open_id['unionid'];
               // $info['open_id'] = $open_id['openid'];
                //$info['update_at'] = time();
                //UserModel::where(['open_id' => $open_id['openid']])->update($info);
                $userInfo = UserModel::userInfo(['phone' => $data['phone_info']['phoneNumber']]);
            }
            //$userInfo['id'] = 1;
            $auth = Auth::instance();
            $userInfo = UserModel::userInfo(['id'=>$userInfo['id']],'id,phone,head_img,nickname,is_certified');
            $token = $auth->token($userInfo['id']);
            $userInfo->setAttr('token', $token);
            //$userData['session_key'] = $session_key;

            $this->member = $userInfo;
            $this->successful('授权注册成功！', $userInfo);
        } else {
            return $data;
        }

    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     *
     * 获取AccessToken
     */
    public function getAccessToken(){
        $appid = config('WeiXin')['appId'];
        $appsecret = config('WeiXin')['appSecret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $res = json_decode($this->httpGet($url),true);
       return $res;
    }

    /**
     * @title 展示微信二维码
     * @Author: Righter.Guo <righter.g@qq.com>
     * @Time: 2021/12/9 13:36
     */
    public function showWxCode()
    {


        //调用微信扫描
        //回调地址，扫码后，页面会自动跳转到这个链接。不需要前端轮询。
        $redirect_uri= $this->request->domain().'/api/login/wxCallback';
        //该回调需要url编码
        $redirect_uri = urlencode($redirect_uri);
        //开放平台的id
        $appID = self::APPID;
        //写死，官方文档写的
        $scope = "snsapi_login";
        //准备向微信发请求
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=扫码后会原样返回给你#wechat_redirect";
        //请求返回的结果(实际上是个html的字符串)就是微信写好的一个二维码的HTML页面。
        $result = file_get_contents($url);

        //替换图片的src才能显示二维码，因为图片没有拼接微信域名，
        $result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
        //此处注释的格式转化，是调试的时候 报错 ，乱码，转化后可以看到汉字报错
//        $result = iconv('gb2312', 'UTF-8//IGNORE', $result);
//        echo $result;
        $result = mb_convert_encoding( $result, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
        //返回json数据，
        $this->successful('展示二维码成功！', $result);


    }

    /**
     *
     * 回调函数
     */
    public function wxCallback()
    {
        $code = $_GET["code"];
        $state = $_GET["state"];
        //开放平台id
        $appid = self::APPID;
        //开放平台秘钥
        $secret = self::SECRET;
        //code是必须的，state我也有用，可以根据自己的业务传参
        if (!empty($code) && !empty($state)) {
            //有code
            //通过code获得 access_token + openid
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
                . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
            $jsonResult = file_get_contents($url);
            $resultArray = json_decode($jsonResult, true);
//            $access_token = $resultArray["access_token"];
//            $openid = $resultArray["openid"];
            $unionid = $resultArray["unionid"];

            //此处是为了查看到底返回了些啥东西
            file_put_contents('./wx_callback111.txt',$resultArray);


            //通过access_token + openid 获得用户信息，此处根据官网资料，获取你想要的东西
//            $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
//            $infoResult = file_get_contents($infoUrl);
//            file_put_contents('./wx_callback222.txt',$infoResult);
//            $infoArray = json_decode($infoResult, true);

            //下面自己的 业务逻辑

            //最后跳转到你想要的页面
            $this->redirect('index/index');

        }

    }


    /**
     * 验证码登录
     */
    public function codeLogin(LoginValidate $request){


        $params = $this->request->post();
        if (!$request->scene('codeLogin')->check($params)){

            $this->fail($request->getError());
        }
//        $code = Cache::get($params['phone']);
//        if ($code == false || $code != $params['code']){
//
//            $this->fail('验证码错误,请重新发送');
//        }

        if ($info = UserModel::where(['phone'=>$params['phone']])->find()){

            $res = $info['id'];
        }else{

            $res = UserModel::userEdit(['phone'=>$params['phone']]);
        }

        $auth = Auth::instance();
        $userInfo = UserModel::userInfo(['id'=>$res],'id,phone,head_img,nickname,is_certified');
        //$userInfo['yunXinToken'] = YunXinModel::refreshToken($userInfo['id']);
        //$token = $auth->token($id);
        $userInfo['token'] = $auth->token($res);
        //$userData['session_key'] = $session_key;

        $this->member = $userInfo;
        $this->successful('登录成功！',$userInfo);

    }


}